package com.n.passwordbook.Utils;

import com.n.passwordbook.LaunchWindow.TmpDataHelper;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;
import java.util.function.Consumer;

public class WindowHelper
{
    public static Object MainContainer;
    public static String MainContainerTypeString;
    public static Scene MainScene;
    public static Stage MainStage;
    public static Object MainController;

    public static <T extends Region> void changeMainSceneRootWithFadeOutAndFadeIn(FXMLLoader nextWindowLoader, Consumer<Object> customFunc) throws IOException
    {
        changeMainSceneRootWithFadeOutAndFadeIn(nextWindowLoader, customFunc, null);
    }

    public static <T extends Region> void changeMainSceneRootWithFadeOutAndFadeIn(FXMLLoader nextWindowLoader, Consumer<Object> customFunc, T preloadedWindow) throws IOException
    {
        //执行动画前预加载
        nextWindowLoader.setClassLoader(TmpDataHelper.CachingClassLoader);
        T nextWindow;
        if (preloadedWindow == null)
        {
            nextWindow = nextWindowLoader.load();
        }
        else
        {
            nextWindow = preloadedWindow;
        }
        MainContainerTypeString = nextWindowLoader.getClass().getTypeName();
        MainController = nextWindowLoader.getController();
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.3), actionEvent -> {
            MainContainer = nextWindow;
            nextWindow.setOpacity(0);
            MainScene.setRoot(nextWindow);
            Timeline timeline1 = new Timeline(new KeyFrame(Duration.seconds(0.5), new KeyValue(nextWindow.opacityProperty(), 1)));
            timeline1.play();
            customFunc.accept(MainController);
        }, new KeyValue(getMainContainer().opacityProperty(), 0)));//此处不执行运行时空对象检查，提高响应速度
        timeline.play();
    }

    private static Region getMainContainer()
    {
        try
        {
            return getMainContainerHelper(Class.forName(MainContainerTypeString), MainContainer);
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static <T extends Region> T getMainContainerHelper(Class<?> clz, Object o)
    {
        return (T) o;
    }
}
